package com.jackrain.nea.fc.vp.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.common.PostHandleEvent;
import com.jackrain.nea.config.Resources;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.cp.api.ChrusersWebQueryCmd;
import com.jackrain.nea.fc.utils.Constants;
import com.jackrain.nea.fc.utils.ObjectToUtil;
import com.jackrain.nea.fc.utils.UserInformation;
import com.jackrain.nea.fc.vp.api.CvipSearchCmd;
import com.jackrain.nea.fc.vp.api.ViewCvipopenSaveCmd;
import com.jackrain.nea.fc.vp.mapper.ViewCvipopenMapper;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.QueryCmd;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySessionImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * @author xuxinshuai
 * @date 2017/11/13
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "vp")
public class ViewCvipopenSaveCmdImpl extends CommandAdapter implements ViewCvipopenSaveCmd {

    @Reference(version = "2", group = "cp")
    private QueryCmd queryCmd;
    @Reference(version = "1.0", group = "cp")
    private ChrusersWebQueryCmd chrusersWebQueryCmd;
    //    @Reference(version = "1.0", group = "vp")
//    private CvipopenSubmitCmd cvipopenSubmitCmd;

    @Reference(version = "1.0", group = "vp")
    private CvipSearchCmd cvipSearchCmd;
    /*@Reference(version = "1.0", group = "vp")
    private CvipSaveCmd cvipSaveCmd;//post
*/

    @Autowired
    PostHandleEvent postHandleEvent;

    private Logger accesLogger = LoggerFactory.getLogger(Constants.ACCESS_PARAM_LOGGER);

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {

        ValueHolder vh = new ValueHolder();
        ViewCvipopenMapper viewCvipopenMapper = ApplicationContextHandle.getBean(ViewCvipopenMapper.class);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"), "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        log.info("ViewCvipopenSaveCmdImpl--jsonObject-->{}",jsonObject);

        if (null == jsonObject || jsonObject.size() == 0) {
            throw new NDSException("参数格式错误！");
        }
        if (!jsonObject.containsKey("data")) {
            throw new NDSException("参数格式错误！");
        }
        if (jsonObject.getJSONArray("data").size() <= 0) {
            throw new NDSException("参数格式错误！");
        }

//        log.debug("----------VIP开卡参数-----------" + jsonObject);
        JSONArray dataArray = jsonObject.getJSONArray("data");
        User user = chrusersWebQueryCmd.getUser(UserInformation.USER_NAME);

        for (int i = 0; i < dataArray.size(); i++) {

            JSONObject param = dataArray.getJSONObject(i);
            //查询是否存在数据
            String cardid = param.getString("ECODE");
            if (ObjectToUtil.isNullOREmpty(cardid)) {
                throw new NDSException("ECODE不能为空！");
            }
            //------------------------查询VIP档案ID-----------------
            JSONObject vipSearchJsonVipid = new JSONObject();
            JSONObject fixedcolumnsJsonVipid = new JSONObject();
            fixedcolumnsJsonVipid.put("ACC.ECODES", cardid);
            JSONArray searchTypeArrayVipid = new JSONArray();
            JSONObject ecodeNameVipid = new JSONObject();
            ecodeNameVipid.put("name", "ACC.ECODES");
            ecodeNameVipid.put("type", "exact");
            searchTypeArrayVipid.add(ecodeNameVipid);
            vipSearchJsonVipid.put("fixedcolumns", fixedcolumnsJsonVipid);
            vipSearchJsonVipid.put("searchtype", searchTypeArrayVipid);
            DefaultWebEvent eventVipid = new DefaultWebEvent("test", new HashMap());
            eventVipid.put("param", vipSearchJsonVipid);
            QuerySessionImpl querySessionVipid = new QuerySessionImpl(user);
            querySessionVipid.setEvent(eventVipid);
            ValueHolder vipValueVipid = cvipSearchCmd.execute(querySessionVipid);
            JSONObject vipJsonVipid = vipValueVipid.toJSONObject();
//            log.info("vipJsonbyecode:" + vipJsonVipid);
            JSONArray idsArrayVipid = vipJsonVipid.getJSONArray("IDS");
            //小于等于0去插入数据
            if (idsArrayVipid.size() <= 0) {

                JSONObject insertJo = new JSONObject();
                //VIP类型
                String viptypegroup_id = param.getString("VP_C_VIPTYPEGROUP_ID");
                if (ObjectToUtil.isNullOREmpty(viptypegroup_id)) {
                    throw new NDSException("VP_C_VIPTYPEGROUP_ID不能为空！");
                }
                Long vipGropuID = viewCvipopenMapper.selecttypegroupid(viptypegroup_id);
                if (vipGropuID == null) {
                    throw new NDSException("FC中不存在" + viptypegroup_id + "VIP类型，VIP开卡失败！");
                }
                insertJo.put("VP_C_VIPTYPEGROUP_ID", vipGropuID);
                //VIP等级
                String vipGrade = param.getString("VP_C_VIPTYPE_ID");
                if (ObjectToUtil.isNullOREmpty(vipGrade)) {
                    throw new NDSException("VP_C_VIPTYPE_ID不能为空！");
                }
                Long vipTypeID = viewCvipopenMapper.selecttypeid(vipGrade);
                if (vipTypeID == null) {
                    throw new NDSException("FC中不存在" + vipGrade + "的等级，VIP开卡失败！");
                }
                insertJo.put("VP_C_VIPTYPE_ID", vipTypeID);
                insertJo.put("ECODE", cardid);
                //姓名
                String ename = param.getString("ENAME");
                if (ObjectToUtil.isNullOREmpty(ename)) {
                    throw new NDSException("ENAME不能为空！");
                }
                insertJo.put("ENAME", ename);
                //性别
                String vipsex = param.getString("SEX");
                if (!ObjectToUtil.isNullOREmpty(vipsex)) {
                    Integer sex = param.getInteger("SEX");
                    if (0 == sex) {
                        insertJo.put("sex", "W");
                    } else if (1 == sex) {
                        insertJo.put("sex", "M");
                    } else if (2 == sex) {
                        insertJo.put("sex", "W");
                    }
                } else {
                    throw new NDSException("SEX不能为空！");
                }
                //生日-年、月、日
                String birthdate = param.getString("BIRTHDATE");
                if (!ObjectToUtil.isNullOREmpty(birthdate)) {
                    try {
                        Date britaday = TypeUtils.castToDate(birthdate);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
                        String sc = simpleDateFormat.format(britaday);
                        insertJo.put("BIRTHDATE", sc);
                    } catch (Exception e) {
                        throw new NDSException("日期格式错误:BIRTHDATE！");
                    }
                } else {
                    throw new NDSException("不能为空:BIRTHDATE！");
                }
                //手机号码
                String mobil = param.getString("MOBIL");
                if (ObjectToUtil.isNullOREmpty(mobil)) {
                    throw new NDSException("MOBIL不能为空！");
                }
                insertJo.put("MOBIL", param.getString("MOBIL"));
                //开卡店仓
                String departmentid = param.getString("CP_C_STORE_ID");
                if (!ObjectToUtil.isNullOREmpty(departmentid)) {

                    HashMap hashMap = new HashMap();
                    hashMap.put("tableName", "CP_C_STORE");
                    hashMap.put("fields", "ID");
                    JSONObject whereJo = new JSONObject();
                    whereJo.put("ECODE", departmentid);
                    hashMap.put("whereKeys", whereJo);
                    hashMap.put("type", HashMap.class);
                    HashMap result = (HashMap) queryCmd.queryTable(hashMap);
                    if (result != null) {
                        Long storeid = (Long) result.get("ID");
                        insertJo.put("CP_C_STORE_ID", storeid);
                    } else {
                        throw new NDSException("FC中不存在对应的VIP开卡店仓，VIP开卡失败！");
                    }
                } else {
                    throw new NDSException("CP_C_STORE_ID不能为空！");
                }
                //地址
                insertJo.put("ADDRESS", param.getString("ADDRESS"));
                //职业
                insertJo.put("JOB", param.getString("JOB"));
                //备注
                insertJo.put("REMARK", param.getString("REMARK"));
                //接受促销信息
                String receieve = param.getString("ISRECEIVEPROM");
                if (!ObjectToUtil.isNullOREmpty(receieve)) {
                    Integer receiveProm = param.getInteger("ISRECEIVEPROM");
                    if (0 == receiveProm) {
                        insertJo.put("ISRECEIVEPROM", "N");
                    } else if (1 == receiveProm) {
                        insertJo.put("ISRECEIVEPROM", "Y");
                    }
                } else {
                    throw new NDSException("ISRECEIVEPROM不能为空！");
                }
                //促销信息
                insertJo.put("RECEIVEWAY", param.getString("RECEIVEWAY"));
                //微信
                insertJo.put("WECHAT", param.getString("WECHAT"));
                //绑定时间
                insertJo.put("bindDate", param.getDate("bindDate"));
                //微信状态
                insertJo.put("wxStatus", param.getString("wxStatus"));
                //邮箱
                insertJo.put("EMAIL", param.getString("EMAIL"));
                //OPENID
                insertJo.put("OPENID", param.getString("OPENID"));
                //身份证
                insertJo.put("ID_CARD", param.getString("ID_CARD"));
                //毕业学校
                insertJo.put("ACADEMIC", param.getString("ACADEMIC"));
                //可用
                String active = param.getString("ISACTIVE");
                if (!ObjectToUtil.isNullOREmpty(active)) {
                    String vipstate = param.getString("ISACTIVE");
                    if ("1".equals(vipstate)) {
                        insertJo.put("ISACTIVE", "Y");
                    } else if ("2".equals(vipstate)) {
                        insertJo.put("ISACTIVE", "N");
                    }
                }
                //是否降级
                String isOff = param.getString("ISOFF");
                if (ObjectToUtil.isNullOREmpty(isOff)) {
                    insertJo.put("ISOFF", "N");
                } else {
                    insertJo.put("ISOFF", isOff);
                }
                //创建人
                insertJo.put("OWNERID", Integer.valueOf(user.getId()).longValue());
                insertJo.put("MODIFIERID", Integer.valueOf(user.getId()).longValue());
                insertJo.put("MODIFIERNAME", user.getName());
                insertJo.put("MODIFIERENAME", user.getEname());
                insertJo.put("OWNERNAME", user.getName());
                insertJo.put("OWNERENAME", user.getEname());
                Timestamp timestamp = new Timestamp(System.currentTimeMillis());
                insertJo.put("CREATIONDATE", timestamp);
                insertJo.put("MODIFIEDDATE", timestamp);
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
                String nowData = df.format(new Date());
                insertJo.put("opendate", nowData);
                insertJo.put("ad_client_id", Integer.valueOf(user.getClientId()).longValue());
                insertJo.put("ad_org_id", Integer.valueOf(user.getOrgId()).longValue());
                insertJo.put("SOURCE", "POS");
                Long vipopenid = Tools.getSequence("VP_C_VIPOPEN");
                insertJo.put("ID", vipopenid);
                //执行插入操作
                insertJo = JSON.parseObject(JSON.toJSONStringWithDateFormat(insertJo, "yyyy-MM-dd HH:mm:ss"), Feature.OrderedField);
                int inserRes = insertData(viewCvipopenMapper, insertJo);
                if (inserRes <= 0) {
                    throw new NDSException(Resources.getMessage("插入失败！"));
                } else {
                    //调开卡提交服务
                    JSONObject jo = new JSONObject();
                    jo.put("objid", vipopenid);
                    jo.put("table", "VP_C_VIPOPEN");
                    QuerySessionImpl userquerySession = new QuerySessionImpl(user);
                    DefaultWebEvent event = new DefaultWebEvent("test", new HashMap());
                    event.put("param", jo);
                    userquerySession.setEvent(event);
                    JSONObject vipOpenJo = new JSONObject();
                    try {
                        vipOpenJo = postHandleEvent.executePostHandle(jo, userquerySession, event, "submit");
//                        ValueHolder openresult = handle.process(jo, userquerySession, event, "submit");
//                        vipOpenJo = openresult.toJSONObject();
                        if (vipOpenJo.containsKey("code") && (vipOpenJo.getLong("code") == -1)) {
                            //删除新增的开卡表数据
                            viewCvipopenMapper.deletevipOpen(vipopenid);
                            throw new NDSException("调用标准服务错误:" + vipOpenJo.getString("message"));
                        }
                    } catch (Exception e) {
                        //删除新增的开卡表数据
                        viewCvipopenMapper.deletevipOpen(vipopenid);
                        StringWriter sw = new StringWriter();
                        PrintWriter pw = new PrintWriter(sw);
                        e.printStackTrace(pw);
                        throw new NDSException("调用标准服务错误" + sw.toString());
                    }
                    vh.put("data", vipOpenJo);
                }

            } else {
                //大于0去更新
                JSONObject updateJo = new JSONObject();
                String viptypegroup_id = param.getString("VP_C_VIPTYPEGROUP_ID");
                if (ObjectToUtil.isNullOREmpty(viptypegroup_id)) {
                    throw new NDSException("VP_C_VIPTYPEGROUP_ID不能为空!");
                }
                Long vipGropuID = viewCvipopenMapper.selecttypegroupid(viptypegroup_id);
                if (vipGropuID == null) {
                    throw new NDSException("FC中不存在" + viptypegroup_id + "VIP类型，VIP开卡失败！");
                }
                //------------------------查询VIP档案ID-----------------
                JSONObject vipSearchJson = new JSONObject();
                JSONObject fixedcolumnsJson = new JSONObject();
                fixedcolumnsJson.put("ACC.ECODES", cardid);
                fixedcolumnsJson.put("ACC.VP_C_VIPTYPEGROUP_ID", vipGropuID);
                JSONArray searchTypeArray = new JSONArray();
                JSONObject ecodeName = new JSONObject();
                ecodeName.put("name", "ACC.ECODES");
                ecodeName.put("type", "exact");
                searchTypeArray.add(ecodeName);
                JSONObject vipTypeName = new JSONObject();
                vipTypeName.put("name", "ACC.VP_C_VIPTYPEGROUP_ID");
                vipTypeName.put("type", "exact");
                searchTypeArray.add(vipTypeName);
                vipSearchJson.put("fixedcolumns", fixedcolumnsJson);
                vipSearchJson.put("searchtype", searchTypeArray);
                DefaultWebEvent event = new DefaultWebEvent("test", new HashMap());
                event.put("param", vipSearchJson);
                QuerySessionImpl querySession = new QuerySessionImpl(user);
                querySession.setEvent(event);
                ValueHolder vipValue = cvipSearchCmd.execute(querySession);
                JSONObject vipJson = vipValue.toJSONObject();
//                log.info("vipJson:" + vipJson);
                if (null == vipJson || (!vipJson.containsKey("IDS"))) {
                    throw new NDSException("未查询到VIPID");
                }
                JSONArray idsArray = vipJson.getJSONArray("IDS");
                if (idsArray.size() != 1) {
                    throw new NDSException("IDS未查询到或存在多条   IDS.SIZE:" + idsArray.size());
                }
                Long vipid = idsArray.getLong(0);
                if (vipid == null) {
                    throw new NDSException("会员ID为空");
                }
//                updateJo.put("ID", vipid);
                if (param.containsKey("ENAME")) {

                    if (ObjectToUtil.isNullOREmpty(param.getString("ENAME"))) {
                        throw new NDSException("ENAME不能为空!");
                    }
                    updateJo.put("ENAME", param.getString("ENAME"));
                }
                if (param.containsKey("SEX")) {
                    if (ObjectToUtil.isNullOREmpty(param.getString("SEX"))) {
                        throw new NDSException("SEX不能为空!");
                    }
                    Integer vipsex = param.getInteger("SEX");
                    if (vipsex == 0) {
                        updateJo.put("SEX", "W");
                    } else if (1 == vipsex) {
                        updateJo.put("SEX", "M");
                    } else if (2 == vipsex) {
                        updateJo.put("SEX", "W");
                    }
                }
                if (param.containsKey("BIRTHDATE")) {

                    if (ObjectToUtil.isNullOREmpty(param.getString("BIRTHDATE"))) {
                        throw new NDSException("BIRTHDATE不能为空!");
                    }
                    try {
                        Date scoreDate = TypeUtils.castToDate(param.getString("BIRTHDATE"));
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
                        String sc = simpleDateFormat.format(scoreDate);
                        updateJo.put("BIRTHDATE", sc);
                    } catch (Exception e) {
                        throw new NDSException("日期格式错误:BIRTHDATE！");
                    }
                }
                if (param.containsKey("MOBIL")) {

                    if (ObjectToUtil.isNullOREmpty(param.getString("MOBIL"))) {
                        throw new NDSException("MOBIL不能为空!");
                    }
                    updateJo.put("MOBIL", param.getString("MOBIL"));
                }
                if (param.containsKey("CP_C_STORE_ID")) {

                    String departmentid = param.getString("CP_C_STORE_ID");
                    HashMap hashMap = new HashMap();
                    hashMap.put("tableName", "CP_C_STORE");
                    hashMap.put("fields", "ID");
                    JSONObject whereJo = new JSONObject();
                    whereJo.put("ECODE", departmentid);
                    hashMap.put("whereKeys", whereJo);
                    hashMap.put("type", HashMap.class);
                    HashMap result = (HashMap) queryCmd.queryTable(hashMap);
                    if (result != null) {
                        Long storeid = (Long) result.get("ID");
                        Long accid = viewCvipopenMapper.selectvipaccid(cardid, vipGropuID, vipid);
                        viewCvipopenMapper.updatevipacc(storeid, accid);
                    } else {
                        throw new NDSException("FC中不存在对应的VIP开卡店仓，VIP开卡失败！");
                    }
                }
                if (param.containsKey("ADDRESS")) {
                    updateJo.put("ADDRESS", param.getString("ADDRESS"));
                }
                if (param.containsKey("JOB")) {
                    updateJo.put("JOB", param.getString("JOB"));
                }
                if (param.containsKey("REMARK")) {
                    updateJo.put("REMARK", param.getString("REMARK"));
                }
                if (param.containsKey("ISRECEIVEPROM")) {
                    if (ObjectToUtil.isNullOREmpty(param.getString("ISRECEIVEPROM"))) {
                        throw new NDSException("ISRECEIVEPROM不能为空!");
                    }
                    Integer recieveprom = param.getInteger("ISRECEIVEPROM");
                    if (0 == recieveprom) {
                        param.put("ISRECEIVEPROM", "N");
                    } else if (1 == recieveprom) {
                        param.put("ISRECEIVEPROM", "Y");
                    }
                }
                if (param.containsKey("RECEIVEWAY")) {
                    updateJo.put("RECEIVEWAY", param.getString("RECEIVEWAY"));
                }
                if (param.containsKey("WECHAT")) {
                    updateJo.put("WECHAT", param.getString("WECHAT"));
                }
                if (param.containsKey("EMAIL")) {
                    updateJo.put("EMAIL", param.getString("EMAIL"));
                }
                if (param.containsKey("OPENID")) {
                    updateJo.put("OPENID", param.getString("OPENID"));
                }
                if (param.containsKey("ID_CARD")) {
                    updateJo.put("ID_CARD", param.getString("ID_CARD"));
                }
                if (param.containsKey("ACADEMIC")) {
                    updateJo.put("ACADEMIC", param.getString("ACADEMIC"));
                }
                if (param.containsKey("ISACTIVE")) {
//                    Integer vipstate = param.getInteger("ISACTIVE");
//                    if (1 == vipstate) {
//                        updateJo.put("ISACTIVE", "Y");
//                    } else if (2 == vipstate) {
//                        updateJo.put("ISACTIVE", "N");
//                    }
                }
                updateJo.put("MODIFIERID", Integer.valueOf(user.getId()).longValue());
                updateJo.put("MODIFIERNAME", user.getName());
                updateJo.put("MODIFIERENAME", user.getEname());
                Timestamp timestamp = new Timestamp(System.currentTimeMillis());
                updateJo.put("MODIFIEDDATE", timestamp);
                //调用标准服务
                JSONObject jo = new JSONObject();
                jo.put("objid", vipid);
                JSONObject fixJo = new JSONObject();
                fixJo.put("VP_C_VIP", updateJo);
                jo.put("fixcolumn", fixJo);
                QuerySessionImpl userquerySession = new QuerySessionImpl(user);
                DefaultWebEvent vipevent = new DefaultWebEvent("test", new HashMap());
                vipevent.put("param", jo);
                userquerySession.setEvent(vipevent);
                accesLogger.info("ViewCvipopenSaveCmdImpl--jo-->{}",jo);
//                log.debug("------------------>>>>>档案修改参数" + jo);
                try {
                    postHandleEvent.executePostHandle(jo, userquerySession, vipevent, "save");
                } catch (Exception e) {
                    e.printStackTrace();
                }
//                cvipSaveCmd.execute(userquerySession);

//                int updateRes = updateData(viewCvipopenMapper, updateJo);
//                if (updateRes <= 0) {
//                    throw new NDSException(Resources.getMessage("更新失败！", querySession.getLocale()));
//                }
            }
        }
        vh.put("status", 0);
        vh.put("message", Resources.getMessage("success"));
        return vh;
    }

    public int insertData(ViewCvipopenMapper viewCvipopenMapper, JSONObject jsonObject) {

        int inserRes = viewCvipopenMapper.insert(jsonObject);
        return inserRes;
    }

    public int updateData(ViewCvipopenMapper viewCvipopenMapper, JSONObject jsonObject) {

        int updateRes = viewCvipopenMapper.update(jsonObject);
        return updateRes;
    }
}
